const dateformat = require('date-fns');
const koa2Req = require('koa2-request')
const Router = require('koa-router');
const common = require('../libs/common');
const moment = require('moment');
const db = require('../libs/db');
const mydb = require('../config/database');
const mydbtran = require('../config/mysqltran');
const response = require('../libs/result');
const random = require('string-random')
let router = new Router();
const addtoken = require('../token/addtoken');
const prate = require('../libs/product_rate');
const lang = require('../lang/language');
const _ = require('underscore');
const bankinfodict = require('../dict/bankinfo');
const eductiondict = require('../dict/eduction');
const loan_remarkdict = require('../dict/loan_remark');
const religiondict = require('../dict/religion');
const usertypedict = require('../dict/usertype');
const orderstatusdict = require('../dict/orderstatus');

/**
 * @api {post} /api/v1/user/getuserinfoconfig  获取用户资料信息配置
 * @apiDescription 获取用户资料信息配置
 * @apiName getuserinfoconfig
 * @apiSampleRequest /api/v1/user/getuserinfoconfig
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/getuserinfoconfig', async ctx => {
    //let{userid,productid}=ctx.request.body;
    let userdata = await ctx.db.query('SELECT name,`key`,type,options,title  FROM customers_customparams where is_active=1',[]);
    userdata.map(function (item, index, input) {
           
        if(item.options==''){
            item.options= []
        }else{
            item.options= item.options.split(",")
        }

       item.title=item.title+"Tidak boleh kosong"
        
           
    })
    response(ctx, 200, userdata,'')

})

/**
 * @api {post} /api/v1/user/loginorregist  短信验证码登录或者注册
 * @apiDescription 短信验证码登录或者注册
 * @apiName loginorregist
 * @apiParam (参数) {String} phone_number   手机号码
 * @apiParam (参数) {String} vercode   验证码
 * @apiParam (参数) {String} channel   包名
 * @apiParam (参数) {String} login_channel   登录包名
 * @apiParam (参数) {String} device_id   安卓id
 * @apiSampleRequest /api/v1/user/loginorregist
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/loginorregist', async ctx => {
    let { phone_number,
        vercode,
        channel,
        login_channel,
        android_id,
    } = ctx.request.body;

    let device_id= android_id;

    //验证传入手机号是否为空
    if (!phone_number || !vercode) {
        response(ctx, 201, '', '手机号或者验证码不能为空');
        return;
    }


    //校验验证码
   
        let vres = await checkvcode(phone_number, vercode);
        vres = JSON.stringify(vres)
        vres = JSON.parse(vres)
        if (vres.code != 200) {
            response(ctx, vres.code, '', vres.msg)
            return;
        }
    

    //验证该手机号是否注册，已经注册则直接登录，未注册则注册并且登录
    let userdata = await ctx.db.query(`SELECT * FROM auth_user where phone_number=?`, [phone_number]);

    if (userdata.length > 0) {
        //登录
        userdata = JSON.stringify(userdata)
        userdata = JSON.parse(userdata)
        let user_id = userdata.id;
        //更新用户登录信息
        let currenttime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        await ctx.db.query(`update auth_user set channel=?,login_channel=?,last_login=?
        where phone_number=?`, [channel, login_channel, currenttime, phone_number]);
        let token = addtoken({ id: userdata.id, logintime: currenttime })
        // ctx.body = common.handleResulte(200, { userid: userdata[0].id, nickname: userdata[0].nickname, mobile: userdata[0].phone_number, applng: ctx.config.applng, countryid: 1 }, '登录成功', '', token)
        response(ctx, 200, { userid: userdata[0].id, nickname: userdata[0].nickname, mobile: userdata[0].phone_number, applng: ctx.config.applng, countryid: 1 }, '登录成功', token)
    } else {
        let lastlogin = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

        try {
            await mydbtran.startTransaction();//开启事务
            //注册并登录
            let insertres = await mydbtran.executeTransaction(`INSERT INTO auth_user (name,nickname, phone_number, password,channel,login_channel,last_login,device_id,is_active,username,created_time,updated_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, [phone_number, phone_number, phone_number, '', channel, login_channel, lastlogin, device_id, 1,phone_number,lastlogin,lastlogin]);

            //插入一条新的借款人信息(待定)
            let insertinfores = await mydbtran.executeTransaction(`INSERT INTO loan_user_info (created_time,updated_time,is_active)values(?,?,?)`, [lastlogin, lastlogin, 1]);

            let insertuserres = await mydbtran.executeTransaction(`INSERT INTO loan_user (created_time,updated_time,mobile,info_id,is_active,name,id_card_number,user_type,education,religion,income,loan_remark)VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`,
                [lastlogin, lastlogin, phone_number, insertinfores.insertId, 1, '', '', 0, 0, 0, '', 0]);
            await mydbtran.stopTransaction();
            insertres = JSON.stringify(insertres)
            insertres = JSON.parse(insertres)
            let token = addtoken({ id: insertres.insertId, logintime: lastlogin })
            response(ctx, 200, { userid: insertres.insertId, nickname: phone_number, mobile: phone_number, applng: ctx.config.applng, countryid: 1 }, '登录成功', token)
        } catch (e) {
            console.log(e);
            response(ctx, 201, '', '登录失败', '')
            return
        }
    }

})

/**
 * @api {post} /api/v1/user/updeviceinfo  上传设备信息
 * @apiDescription 上传设备信息
 * @apiName upinfo
 * @apiParam (参数) {String} device   设备信息
 * @apiParam (参数) {String} contacts    联系人列表({"data":[{"contact_times":0,"lastUpdate":"1573542910507","last_contact_time":"0","name":"iiii","nickname":"","number":[{"last_time_used":"0","number":"15388455457","time_used":0,"type_label":"Seluler"}],"relation":"iiii","status":""}],"earliestTime":"0","latestTime":0,"protocolName":"CONTACT","protocolVersion":"V_1_0","totalNumber":38,"versionName":"2.1.0"})
 * @apiParam (参数) {String} android_id   android_id
 * @apiParam (参数) {String} app_list   应用列表([{"packageName":"com.github.shadowsocks"}])
 * @apiParam (参数) {String} brand    手机品牌
 * @apiParam (参数) {String} gps    GPS定位信息({"altitude":0,"createTime":1577237511024,"latitude":30.341885,"longitude":120.10869})
 * @apiParam (参数) {String} imei    imei
 * @apiParam (参数) {String} phone_model    手机型号
 * @apiParam (参数) {String} uuid    uuid
 * @apiParam (参数) {String} user_id    user_id
 * @apiSampleRequest /api/v1/user/loginorregist
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/updeviceinfo', async ctx => {
    try {
        let input = ctx.request.body;
        console.log(input);
        // let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [input.user_id]);
        // loan_user = JSON.stringify(loan_user)
        // loan_user = JSON.parse(loan_user)
        //获取客户端ip
        let ip = ctx.request.ip;
        let userdevice = await ctx.db.query(`select * from device_info where user_id=?`, [parseInt(input.user_id)]);
        console.log(userdevice);
        if (userdevice.length == 0) {
            //插入设备信息
          let insertres=  await ctx.db.query(`insert device_info(device,contacts,android_id,user_id,app_list,brand,gps,imei,phone_model,uuid,ip) 
          VALUES(?,?,?,?,?,?,?,?,?,?,?)`, [input.device, input.contacts, input.android_id, input.user_id, input.app_list, input.brand, input.gps, input.imei, input.phone_model, input.uuid, ip]);

          console.log(insertres);
            response(ctx, 200);
            return;
        } else {
            await ctx.db.query(`update device_info set device=?,contacts=?,android_id=?,app_list=?,brand=?,gps=?,imei=?,phone_model=?,uuid=?,ip=? 
        where user_id=?`, [input.device, input.contacts, input.android_id, input.app_list, input.brand, input.gps, input.imei, input.phone_model, input.uuid, ip, input.user_id,]);
            response(ctx, 200);
            return;
        }
    } catch (error) {
        console.log(error)
        response(ctx, 201);
        return;
    }


})


/**
 * @api {post} /api/v1/user/sendvcode  发送注册或者登录验证码
 * @apiDescription 发送注册或者登录验证码
 * @apiName sendvcode
 * @apiParam (参数) {String} phone_number   手机号码
 * @apiSampleRequest /api/v1/user/sendvcode
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/sendvcode', async ctx => {
    console.log(ctx.request);
    let { phone_number } = ctx.request.body;
    //验证恶意刷验证码

    //验证传入手机号是否为空
    if (!phone_number) {
        response(ctx, 201, '', '手机号不能为空');
        return;
    }
    //
    //校验上次发送短信的时间,判断是否能再次发送短信
    let lastsendtime = await ctx.db.query(`SELECT created_time from sms_log where mobile=? order by created_time desc LIMIT 1`, [phone_number]);
    if (lastsendtime.length > 0) {
        lastsendtime = JSON.stringify(lastsendtime)
        lastsendtime = JSON.parse(lastsendtime)
        const currenttime = new Date();
        lastsendtime = new Date(lastsendtime[0].created_time)
        console.log(lastsendtime);
        let diffminutes = dateformat.differenceInMinutes(currenttime, lastsendtime)
        if (diffminutes < 1) {
            response(ctx, 201, '', '1分钟内不能重复获取验证码');
            return;
        }
    }
    //发送验证码
    let validation = '';
    for(let i=0;i<6;i++){
        validation+=Math.floor(Math.random()*10).toString();
    }

    let vcontent = '[EkspresCash]Kode otentikasi adalah:' + validation
    console.log(phone_number + '短信验证码为：' + validation);
    let jsondata = {
        'account': ctx.config.smsuid,
        'password': ctx.config.smspwd,
        'msg': vcontent,
        'mobile': phone_number
    }
    //数据库记录验证码发送
    let sendres = await sendmessage(jsondata, ctx.config.smsurl);
    sendres = JSON.stringify(sendres)
    sendres = JSON.parse(sendres)
    if (sendres.statusCode != 200) {
        response(ctx, 201, '', '短信服务器故障');
        return;
    }

    let insertres = await ctx.db.query(`INSERT INTO sms_log (created_time, mobile, content, code) VALUES(?,?,?,?)`, [moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), phone_number, validation, sendres.body.code]);
    if (!insertres) {
        response(ctx, 201, '', '系统错误');
        return;
    }
    response(ctx, 200, '', '短信发送成功');
    return;
})

/**
 * @api {post} /api/v1/user/getloanuser  获取借款人用户基础资料
 * @apiDescription 获取借款人用户资料
 * @apiName getloanuser
 * @apiParam (参数) {String} user_id   用户id
 * @apiSampleRequest /api/v1/user/getloanuser
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/getloanuser', async ctx => {
    let { user_id } = ctx.request.body;
    //根据手机号获取借款人信息
    let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);

    if (loan_user.length == 0) {
        response(ctx, 201, '', '该用户不存在');
        return;
    }

    loan_user = JSON.stringify(loan_user)
    loan_user = JSON.parse(loan_user)

    let userloandata = await ctx.db.query(`SELECT name,id_card_number,user_type,education,income,religion FROM loan_user WHERE id=?`, [loan_user[0].id]);

    if (userloandata.length == 0) {
        response(ctx, 201, '', '该用户没有资料');
        return;
    }
    //let eduction = [{ name: "DIPLOMA_I", val: 1 }, { name: "DIPLOMA_II", val: 2 }, { name: "DIPLOMA_III", val: 3 }, { name: "SD", val: 4 }, { name: "SLTP", val: 5 }, { name: "SLTA", val: 6 }, { name: "S1", val: 7 }, { name: "S2", val: 8 }, { name: "S3", val: 9 }]
    //let religion = [{ name: "Islam", val: 1 }, { name: "Kekristenan", val: 2 }, { name: "Katolik", val: 3 }, { name: "Agama Hindu", val: 4 }, { name: "Agama Buddha", val: 5 }, { name: "Konfusianisme", val: 6 }]
    //let loan_remark = [{ name: "Konsumsi harian", val: 1 }, { name: "Bepergian", val: 2 }, { name: "Dekorasi", val: 3 }, { name: "Pendidikan", val: 4 }, { name: "Medis", val: 5 }, { name: "Perputaran modal", val: 6 }]
    //let usertype = [{ name: "Untuk bekerja", val: 1 }, { name: "Pelajar", val: 2 }]
    eductiondict.map(function (item, index, input) {

        if (item.val == userloandata[0].education) {
            userloandata[0].education_msg = item.name
        }

    })
    religiondict.map(function (item, index, input) {

        if (item.val == userloandata[0].religion) {
            userloandata[0].religion_msg = item.name
        }

    })

    usertypedict.map(function (item, index, input) {

        if (item.val == userloandata[0].user_type) {
            userloandata[0].user_type_msg = item.name
        }

    })
    response(ctx, 200, userloandata[0], '用户资料');
})

/**
 * @api {post} /api/v1/user/updatebaseinfo  修改借款人用户基础资料
 * @apiDescription 修改借款人用户基础资料
 * @apiName updatebaseinfo
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} name   姓名
 * @apiParam (参数) {String} id_card_number   身份证
 * @apiParam (参数) {Number} user_type   用户类型
 * @apiParam (参数) {Number} education   教育
 * @apiParam (参数) {String} income   收入
 * @apiParam (参数) {Number} religion   宗教
 * @apiSampleRequest /api/v1/user/updatebaseinfo
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/updatebaseinfo', async ctx => {
    try {
        let { user_id, name, id_card_number, user_type, education, income, religion } = ctx.request.body;
        //根据手机号获取借款人信息
        let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);

        if (loan_user.length == 0) {
            let authuser = await ctx.db.query(`select * from auth_user id=?`, [user_id]);

            let currenttime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
            await ctx.db.query(`insert into loan_user (name,id_card_number,user_type,education,income,religion,created_time,updated_time,is_active,loan_remark,mobile)values(?,?,?,?,?,?,?,?,?,?,?)`, [name, id_card_number, user_type, education, income, religion, loan_user[0].id], currenttime, currenttime, 1, '', authuser[0].phone_number);
        }
        await ctx.db.query(`update loan_user set name=?,id_card_number=?,user_type=?,education=?,income=?,religion=? where id=?`, [name, id_card_number, user_type, education, income, religion, loan_user[0].id]);
        response(ctx, 200, '', '修改成功');
    } catch (error) {
        console.log(error)
        response(ctx, 201, '', '修改失败');
    }
})


/**
 * @api {post} /api/v1/user/getloanuserbank  获取借款人用户银行卡
 * @apiDescription 获取借款人用户银行卡
 * @apiName getloanuserbank
 * @apiParam (参数) {Number} user_id   用户id
 * @apiSampleRequest /api/v1/user/getloanuserbank
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/getloanuserbank', async ctx => {
    let { user_id } = ctx.request.body;
    let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);

    if (loan_user.length == 0) {
        response(ctx, 200, [], '银行卡信息');
        return;
    }

    loan_user = JSON.stringify(loan_user)
    loan_user = JSON.parse(loan_user)

    let userloandata = await ctx.db.query(`select id,bank_code,bank_account,opening_bank,bank_name,bank_user_name from loan_bank_info where owner_id=? and status=0`, [loan_user[0].id]);

    // if (userloandata.length == 0) {
    //     response(ctx, 201, '', '该用户没有银行卡信息');
    //     return;
    // }
    response(ctx, 200, userloandata, '银行卡信息');
})





/**
 * @api {post} /api/v1/user/delloanuserbank  删除借款用户银行卡
 * @apiDescription 删除借款用户银行卡
 * @apiName delloanuserbank
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {Number} id   银行卡id
 * @apiSampleRequest /api/v1/user/delloanuserbank
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/delloanuserbank', async ctx => {
    let { user_id, id } = ctx.request.body;

    //根据手机号获取借款人信息
    let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);

    if (loan_user.length == 0) {
        response(ctx, 201, '', '该用户不存在');
        return;
    }

    loan_user = JSON.stringify(loan_user)
    loan_user = JSON.parse(loan_user)

    await ctx.db.query(`update  loan_bank_info set status=-1  where id=? and owner_id=? and status=0`, [id, loan_user[0].id]);
    ctx.body = common.handleResulte(200, '', '删除成功')
})


/**
 * @api {post} /api/v1/user/checkpersondata  资料完整度
 * @apiDescription 检测用户资料完整度
 * @apiName checkpersondata
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} type   页面类型： 1：身份认证 2： 个人信息 3：选择银行卡
 * @apiSampleRequest /api/v1/user/checkpersondata
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/checkpersondata', async ctx => {
    let { user_id, type } = ctx.request.body;
    if (!user_id || user_id == 'undefined' || user_id == '') {
        response(ctx, 201, '', '用户id不能为空');
        return;
    }
    if (!type || type == 'undefined' || type == '') {
        response(ctx, 201, '', '页面类型不能为空');
        return;
    }
    let userdata = await db.queryone(ctx, 'auth_user', 'phone_number', { id: user_id });
    if (!userdata) {
        response(ctx, 201, '', '未找到用户信息');
        return;
    }

    let loanuser=await ctx.db.query("SELECT  b.id  FROM  auth_user a,loan_user b WHERE a.phone_number=b.mobile AND a.id=?",[user_id])

    //获取动态配置信息
    let customers_customparams = await ctx.db.query('SELECT name,`key`,type,options  FROM customers_customparams where is_active=1',[]);
    let result = [];
    let i=0;
    customers_customparams.map(function(item,index,input){
      result[i]=item.key;
      i++
    });
    let qstr=result.join(',lui.');
    qstr='lui.'+qstr;
    if (type == '1') {
        let selectStr = 'name,id_card_number,user_type,idcard_image_front,idcard_image_hand';

        //借款人信息
        let data = await db.queryone(ctx, 'loan_user', selectStr, { mobile: userdata.phone_number});
        
        let validateData=await ctx.db.query(`SELECT lu.name,lu.id_card_number,lu.idcard_image_hand,lu.user_type,lu.id,lu.loan_remark,
        lu.education,lu.income,lu.religion,
        `+qstr+`
        FROM  loan_user AS  lu 
       LEFT JOIN  loan_user_info AS  lui ON lui.id= lu.info_id
       WHERE  lu.mobile='${userdata.phone_number}' GROUP BY  lu.id`)

       let cusersqlstr='select  lc.id,lc.name as cname, lc.mobile as cmobile, lc.relation from  loan_contacts lc where lc.owner_id=?';
       let contactsuserdata= await ctx.db.query(cusersqlstr,[loanuser[0].id]);
       if(!data){
           data={};
       }
       data.cuserid1='';
       data.cname1='';
       data.cmobile1='';
       data.relation1='';

       data.cuserid2='';
       data.cname2='';
       data.cmobile2='';
       data.relation2='';

       if(contactsuserdata.length>0){
           data.cuserid1=contactsuserdata[0].id;
           data.cname1=contactsuserdata[0].cname
           data.cmobile1=contactsuserdata[0].cmobile
           data.relation1=contactsuserdata[0].relation
       }

       if(contactsuserdata.length>1){
           data.cuserid2=contactsuserdata[1].id;
           data.cname2=contactsuserdata[1].cname
           data.cmobile2=contactsuserdata[1].cmobile
           data.relation2=contactsuserdata[1].relation
       }


    //    validateData = JSON.stringify(validateData)
    //    validateData = JSON.parse(validateData)
    //     data.isvalidate = common.validateObj(validateData[0]);
        data.isvalidate = false;
        if (data.idcard_image_front)
            data.idcard_image_front = ctx.config.fileurl + data.idcard_image_front;
        if (data.idcard_image_reverse)
            data.idcard_image_reverse = ctx.config.fileurl + data.idcard_image_reverse;
        if (data.idcard_image_hand)
            data.idcard_image_hand = ctx.config.fileurl + data.idcard_image_hand;
        if (data.user_type == 1) {
            data['user_type_msg'] = "Untuk bekerja";
        } else if (data.user_type == 2) {
            data['user_type_msg'] = "Pelajar";
        }
        //data.usercontacts=contactsuserdata
        response(ctx, 200, data, '返回身份认证信息');
        return;
    }
    else if (type == '2') {


        let sqlStr = `SELECT lu.idcard_image_hand,lu.user_type,lu.id,lu.loan_remark,lu.education,lu.income,lu.religion,
        `+qstr+`,lui.familyCard,lui.env_path
        FROM  loan_user AS  lu 
       LEFT JOIN  loan_user_info AS  lui ON lui.id= lu.info_id
       WHERE  lu.mobile='${userdata.phone_number}'
       GROUP BY  lu.id`;
      
        let data = await ctx.db.query(sqlStr);
        let cusersqlstr='select  lc.id,lc.name as cname, lc.mobile as cmobile, lc.relation from  loan_contacts lc where lc.owner_id=?';
        let contactsuserdata= await ctx.db.query(cusersqlstr,[loanuser[0].id]);
        data.map(function (item, index, input) {
            item.idcard_image_hand = ctx.config.fileurl + item.idcard_image_hand

            item.familyCard = ctx.config.fileurl + item.familyCard
            item.env_path = ctx.config.fileurl + item.env_path
            eductiondict.map(function (ods, index, input) {
                if (ods.val == item.education) {
                    item.endu_msg = ods.name
                }
            });

            religiondict.map(function (rds, index, input) {
                if (rds.val == item.religion) {
                    item.religion_mgs = rds.name
                }
            });

            loan_remarkdict.map(function (rmk, index, input) {
                if (rmk.val == item.loan_remark) {
                    item.loan_remark_msg = rmk.name
                }
            });
            usertypedict.map(function (ut, index, input) {
                if (ut.val == item.user_type) {
                    item.user_type_msg = ut.name
                }
            });
        })

        data=data[0]
        //data.isvalidate = common.validateObj(data);
        data.isvalidate = false;
        //data.usercontacts=contactsuserdata
        data.cuserid1='';
        data.cname1='';
        data.cmobile1='';
        data.relation1='';

        data.cuserid2='';
        data.cname2='';
        data.cmobile2='';
        data.relation2='';
        //省市县特殊
        let addressdata = await ctx.db.query(`select lui.* from loan_user_info lui,loan_user lu where lu.info_id=lui.id and lu.mobile='${userdata.phone_number}'`);
        addressdata=addressdata[0];
        if(data.company_province){
            data.company_province=addressdata.company_province+'/'+addressdata.company_city+'/'+addressdata.company_area+'/'+addressdata.company_district
        }

        if(data.province){
            data.province=addressdata.province+'/'+addressdata.city+'/'+addressdata.area+'/'+addressdata.district
        }

        if(contactsuserdata.length>0){
            data.cuserid1=contactsuserdata[0].id;
            data.cname1=contactsuserdata[0].cname
            data.cmobile1=contactsuserdata[0].cmobile
            data.relation1=contactsuserdata[0].relation
        }

        if(contactsuserdata.length>1){
            data.cuserid2=contactsuserdata[1].id;
            data.cname2=contactsuserdata[1].cname
            data.cmobile2=contactsuserdata[1].cmobile
            data.relation2=contactsuserdata[1].relation
        }
        response(ctx, 200, data, '返回个人信息');
        return;
    }
    else if (type == '3') {
        let sqlStr = `SELECT lb.id,lb.bank_user_name,lb.bank_name,lb.bank_account FROM loan_user lu RIGHT JOIN loan_bank_info lb ON lu.id= lb.owner_id 
        WHERE lu.mobile='${userdata.phone_number}'`;
        let data = await ctx.db.query(sqlStr);
        data = data.map((a) => {
            a.bank_account = '尾号' + a.bank_account.substr(a.bank_account.length - 4, 4);
            return a;
        });
        response(ctx, 200, data, '返回银行卡信息');
    }
})

/**
 * @api {post} /api/v1/user/savebank  保存银行卡信息
 * @apiDescription 保存银行卡信息
 * @apiName savebank
 * @apiParam (参数) {String} user_id  用户id
 * @apiParam (参数) {String} bank_name 银行名称   
 * @apiParam (参数) {String} bank_user_name 持卡人姓名   
 * @apiParam (参数) {String} bank_account 银行卡号  
 * @apiParam (参数) {String} bank_code 银行code  
 * @apiParam (参数) {String} opening_bank  开户行名字  
 * @apiSampleRequest /api/v1/user/savebank
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/savebank', async ctx => {
    let { user_id, bank_name, bank_user_name, bank_account, bank_code, opening_bank,bank_id } = ctx.request.body;
    if (!user_id || user_id == 'undefined' || user_id == '') {
        response(ctx, 201, '', '用户id不能为空');
        return;
    }
    if (!bank_name || bank_name == 'undefined' || bank_name == '') {
        response(ctx, 201, '', '银行名称不能为空');
        return;
    }
    if (!bank_user_name || bank_user_name == 'undefined' || bank_user_name == '') {
        response(ctx, 201, '', '持卡人姓名不能为空');
        return;
    }
    if (!bank_account || bank_account == 'undefined' || bank_account == '' || bank_account.length < 16) {
        response(ctx, 201, '', '银行卡号不正确');
        return;
    }
    let userdata = await db.queryone(ctx, 'auth_user', 'phone_number', { id: user_id });
    if (!userdata) {
        response(ctx, 201, '', '未找到用户信息');
        return;
    }
    let mobile = userdata.phone_number;
    let loan_user = await db.queryone(ctx, 'loan_user', 'id', { mobile: mobile });
    // 判断同一银行同一用户是否已添加
    let loan_bank_info = await db.queryone(ctx, 'loan_bank_info', 'id,bank_account', { id:bank_id });
    let utime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    if (loan_bank_info) {

        let strsql = `Update loan_bank_info set updated_time=?,bank_name=?, bank_user_name= ?, bank_account=?,bank_code=?,opening_bank=? where id =?`;
        await ctx.db.query(strsql, [utime, bank_name, bank_user_name, bank_account, bank_code, opening_bank, loan_bank_info.id]);
    } else {
        let loan_bank_info_isexist = await db.queryone(ctx, 'loan_bank_info', 'id,bank_account', { bank_name: bank_name, owner_id: loan_user.id,bank_account: bank_account });
        if(loan_bank_info_isexist){
            response(ctx, 201, '', '该银行卡已存在');
            return;
        }else{
            await ctx.db.query(`INSERT INTO loan_bank_info (created_time, updated_time, is_active,opening_bank,status,reason,bank_code, bank_name, bank_user_name, bank_account, owner_id) 
            VALUES(?,?,?,?,?,?,?,?,?,?,?)`, [utime, utime, 1, opening_bank, 0, '', bank_code, bank_name, bank_user_name, bank_account, loan_user.id]);
        }
        
    }

    response(ctx, 200, '', '保存银行卡信息成功');
})

/**
 * @api {post} /api/v1/user/saveuserloan  保存借款身份认证
 * @apiDescription 保存借款身份认证
 * @apiName saveuserloan
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} imei   设备号
 * @apiParam (参数) {String} name 用户姓名   
 * @apiParam (参数) {String} id_card_number 身份证号码   
 * @apiParam (参数) {String} user_type 用户类型   
 * @apiParam (参数) {String} idcard_image_front 身份证正面照片   
 * @apiParam (参数) {String} idcard_image_reverse 身份证背面照片   
 * @apiParam (参数) {String} idcard_image_hand 手持身份证照片   
 * @apiSampleRequest /api/v1/user/saveuserloan
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/saveuserloan', async ctx => {
    let { user_id, imei, name, id_card_number, user_type, idcard_image_front, idcard_image_reverse, idcard_image_hand } = ctx.request.body;
    if (!user_id || user_id == 'undefined' || user_id == '') {
        response(ctx, 201, '', '用户id不能为空');
        return;
    }
    if (!name || name == 'undefined' || name == '') {
        response(ctx, 201, '', '请输入用户姓名');
        return;
    }
    if (!id_card_number || id_card_number == 'undefined' || id_card_number == '') {
        response(ctx, 201, '', '请输入身份证号码');
        return;
    }
    if (!user_type || user_type == 'undefined' || user_type == '') {
        response(ctx, 201, '', '请选择用户类型');
        return;
    }
    if (!idcard_image_front || idcard_image_front == 'undefined' || idcard_image_front == '') {
        response(ctx, 201, '', '请上传身份证正面照片');
        return;
    }
    // if (!idcard_image_reverse || idcard_image_reverse == 'undefined' || idcard_image_reverse == '') {
    //     response(ctx, 201, '', '请上传身份证背面照片');
    //     return;
    // }
    if (!idcard_image_hand || idcard_image_hand == 'undefined' || idcard_image_hand == '') {
        response(ctx, 201, '', '请上传手持身份证照片');
        return;
    }
    let userdata = await db.queryone(ctx, 'auth_user', 'phone_number', { id: user_id });
    if (!userdata) {
        response(ctx, 201, '', '未找到用户信息');
        return;
    }
    let mobile = userdata.phone_number;
    let loan_user = await db.queryone(ctx, 'loan_user', 'id', { mobile: mobile});
    // 用户信息是否存在，存在则更新
    let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    if (loan_user) {

        let strsql = `Update loan_user set updated_time= '${datenow}',imei='${imei}',name='${name}', id_card_number= '${id_card_number}', user_type=${user_type}`;
        if(idcard_image_hand.indexOf(ctx.config.fileurl)==-1){
            strsql+=`,idcard_image_hand='${idcard_image_hand}'`
        }
        if(idcard_image_front.indexOf(ctx.config.fileurl)==-1){
            strsql+=`,idcard_image_front='${idcard_image_front}'`
        }

        if(idcard_image_reverse.indexOf(ctx.config.fileurl)==-1){
            strsql+=`,idcard_image_reverse='${idcard_image_reverse}'`
        }

        strsql+=` where id = ${loan_user.id}`;

       
        await ctx.db.query(strsql);
    } else {
        await ctx.db.query(`INSERT INTO loan_user (created_time,updated_time,is_active,education,religion,income,loan_remark,mobile,imei, name, id_card_number, user_type,idcard_image_front,idcard_image_reverse,idcard_image_hand) 
    VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, [datenow, datenow, 1, 1, 1, '', 1, mobile + '34', imei, name, id_card_number, user_type, idcard_image_front, idcard_image_reverse, idcard_image_hand]);
    }

    response(ctx, 200, '', '保存身份认证信息成功');
})

/**
 * @api {post} /api/v1/user/userqualification  用户前置问询
 * @apiDescription 用户前置问询
 * @apiName userqualification
 * @apiParam (参数) {String} user_id   用户id   
 * @apiParam (参数) {String} productid   产品id   
 * @apiSampleRequest /api/v1/user/userqualification
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/userqualification', async ctx => {
    try {
        
      let{user_id,productid}=ctx.request.body;

        //根据手机号获取借款人信息
      let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);
      let deviceinfo=await ctx.db.query(`select * from device_info where user_id=?`, [user_id]);
      let product=await ctx.db.query(`select * from products_product where id=?`, [productid]);
    
      //loan_user=JSON.stringify(loan_user);
      let postobj={
          appId:product[0].appid,
          credentialNo:loan_user[0].id_card_number,
          credentialType:'KTP',
          imei:deviceinfo[0].imei||random(16),
          mobile:loan_user[0].mobile,
          proudctIds:[product[0].partner_id]
      };
     
       postobj = common.signjsapi(postobj, product[0].key);
        var options = {
            method: 'post',
            url: product[0].domain + '/apply_api/qualification',
            json:postobj,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        }
       
        let res = await koa2Req(options);
        //let  res = await common.webclient(product[0].domain + '/apply_api/qualification', postobj, 'post', ctx);
        // res = JSON.stringify(res)
        // res = JSON.parse(res)
        if(res.body.code==0){
           if(res.body.data[0].isReceived){
            response(ctx, 200, '', '');
           }else{
            response(ctx, 201, '', '无法借款');
           }
        }else{
            response(ctx, 201, '', '无法借款');
        }

    } catch (error) {
        response(ctx, 201, '', '无法借款');
    }
   
})

/**
 * @api {post} /api/v1/user/saveuserinfo  保存借款个人信息
 * @apiDescription 保存借款个人信息
 * @apiName saveuserinfo
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} imei   设备号
 * @apiParam (参数) {String} loan_remark 借款用途   
 * @apiParam (参数) {String} education 教育程度   
 * @apiParam (参数) {String} income 月收入   
 * @apiParam (参数) {String} religion 宗教信仰  
 * @apiParam (参数) {String} cuserid1 紧急联系人id1    
 * @apiParam (参数) {String} cname1 紧急联系人姓名1   
 * @apiParam (参数) {String} cmobile1 紧急联系人号码1   
 * @apiParam (参数) {String} relation1 紧急联系人关系1
  * @apiParam (参数) {String} cuserid2 紧急联系人id2   
 * @apiParam (参数) {String} cname2 紧急联系人姓名2
 * @apiParam (参数) {String} cmobile2 紧急联系人号码2   
 * @apiParam (参数) {String} relation2 紧急联系人关系2      
 * @apiParam (参数) {String} company_name 公司名称
 * @apiParam (参数) {String} company_province 公司省份
 * @apiParam (参数) {String} company_phone 公司电话
 * @apiParam (参数) {String} company_city 公司城市      
 * @apiParam (参数) {String} profession 职业
 * @apiParam (参数) {String} salary 薪水
 * @apiParam (参数) {String} full_name 全名
 * @apiParam (参数) {String} first_name first_name
 * @apiParam (参数) {String} middle_name middle_name 
 * @apiParam (参数) {String} last_name Last Name
 * @apiParam (参数) {String} birthday 生日
 * @apiParam (参数) {String} province 省
 * @apiParam (参数) {String} city 市
 * @apiParam (参数) {String} district 区
 * @apiParam (参数) {String} area 县
 * @apiParam (参数) {String} address 地址
 * @apiParam (参数) {String} gender 性别
 * @apiParam (参数) {String} marital_status 婚姻状况
 * @apiParam (参数) {String} children_number 孩子数量
 * @apiParam (参数) {String} residence_duration 居住时间
 * @apiParam (参数) {String} family_name_in_lan 家族姓名
 * @apiParam (参数) {String} email 邮件
 * @apiParam (参数) {String} motherName 母亲名字
 * @apiParam (参数) {String} jobType 工作类型
 * @apiParam (参数) {String} workTime 工作年限
 * @apiParam (参数) {String} bankPhone 银行电话
 * @apiParam (参数) {String} company_address 公司地址   
 * @apiParam (参数) {String} env_path 工作环境照片   
 * @apiParam (参数) {String} best_path 活体识别最佳照片url
 * @apiParam (参数) {String} env_path 用户环境照片url
 * @apiParam (参数) {String} company_district 公司区
 * @apiParam (参数) {String} company_area 公司所在县
 * @apiParam (参数) {String} familyCard 家庭卡照片
 * @apiSampleRequest /api/v1/user/saveuserinfo
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/saveuserinfo', async ctx => {
    
     let reqbodys=ctx.request.body;
     
     if(reqbodys.cmobile1==reqbodys.cmobile2){
        response(ctx, 201, '', '紧急联系人不能为同一人');
        return;
     }

    if (!reqbodys.user_id || reqbodys.user_id == 'undefined' || reqbodys.user_id == '') {
        response(ctx, 201, '', '用户id不能为空');
        return;
    }
  
    let userdata = await db.queryone(ctx, 'auth_user', 'phone_number', { id: reqbodys.user_id });
    if (!userdata) {
        response(ctx, 201, '', '未找到用户信息');
        return;
    }
    let mobile = userdata.phone_number;
    let loan_user = await db.queryone(ctx, 'loan_user', 'id,info_id', { mobile: mobile });
    let info_id;
    let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

    //获取动态配置资料参数
    let customers_customparams = await ctx.db.query('SELECT name,`key`,type,options  FROM customers_customparams where is_active=1',[]);
    let cresult = [];
   
    let i=0;
    customers_customparams.map(function(item,index,input){
        cresult[i]=item.key;
      i++
    });


    let result = [];
    let updatevalues=[];
    let insertvalstr=[];
    let insertvalues=[];

    for (const key in reqbodys) {
        if(cresult.indexOf(key)>-1){
            //console.log(key)
            result.push(key);
            if(reqbodys[key].indexOf(ctx.config.fileurl)>-1){
                reqbodys[key]=reqbodys[key].replace(ctx.config.fileurl,'')
            }
            updatevalues.push(reqbodys[key])
            insertvalstr.push('?')
            insertvalues.push(reqbodys[key])
        }
       
    }
    // 保存借款用户补充资料
    if (loan_user && loan_user.info_id) {
        let updatestr='update loan_user_info set '+result.join('=?,')+'=?,updated_time=? where id=?';
        console.log(updatestr);
        //updatevalues.push(reqbodys.familyCard)
        //updatevalues.push(reqbodys.env_path)
        updatevalues.push(datenow)
        updatevalues.push(loan_user.info_id)
        console.log(updatevalues);
      await ctx.db.query(updatestr,updatevalues);

    } else {
        insertvalstr.push('?','?')
   
        let insertstr='insert into loan_user (' +result.join(',')+',familyCard,env_path,created_time,is_active) values('+insertvalstr.join(',')+')';
    
        insertvalues.push(datenow,1);
       await ctx.db.query(insertstr,insertvalues);

        let louser = await db.queryone(ctx, 'loan_user_info', 'id', { company_name: reqbodys.company_name, company_address: reqbodys.company_address, env_path: reqbodys.env_path, familyCard: reqbodys.familyCard });
        if (louser)
            info_id = louser.id;
    }

    console.log(reqbodys.company_province)
    if(reqbodys.company_province){
        let crarr=reqbodys.company_province.split('/');
        console.log(crarr)
        await ctx.db.query(`update loan_user_info set company_province=?,company_city=?,company_area=?,company_district=? where id=?`,[crarr[0],crarr[1],crarr[2],crarr[3],loan_user.info_id])
        
    }
    console.log(reqbodys.province)
    if(reqbodys.province){
        let crarr=reqbodys.province.split('/');
        console.log(crarr)
        await ctx.db.query(`update loan_user_info set province=?,city=?,area=?,district=? where id=?`,[crarr[0],crarr[1],crarr[2],crarr[3],loan_user.info_id])
        
    }

    // 保存用户信息，存在则更新
    if (loan_user) {
        let strsql = `update loan_user set updated_time='${datenow}',imei='${reqbodys.imei}',loan_remark='${reqbodys.loan_remark}', education= '${reqbodys.education}', income='${reqbodys.income}',religion='${reqbodys.religion}' where id = ${loan_user.id}`;
        await ctx.db.query(strsql);
    } else {
        await ctx.db.query(`insert into loan_user (created_time,updated_time,mobile, imei, loan_remark, income,religion, is_active,info_id) 
        VALUES(?,?,?,?,?,?,?,?,?)`, [datenow, datenow,mobile, reqbodys.imei, reqbodys.loan_remark, reqbodys.education, reqbodys.income, reqbodys.religion, 1, info_id]);
        loan_user = await ctx.db.queryone(ctx, 'loan_user', 'id', { mobile: mobile });
    }

    // 保存联系人信息
    let loan_contacts = await db.queryone(ctx, 'loan_contacts', '*', { owner_id: loan_user.id });
    if (loan_contacts) {
        let strsql = `Update loan_contacts set name='${reqbodys.cname1}',mobile='${reqbodys.cmobile1}', relation= '${reqbodys.relation1}' where id = ${reqbodys.cuserid1}`;
        await ctx.db.query(strsql);

        let strsql2 = `Update loan_contacts set name='${reqbodys.cname2}',mobile='${reqbodys.cmobile2}', relation= '${reqbodys.relation2}' where id = ${reqbodys.cuserid2}`;
        await ctx.db.query(strsql2);

    } else {
        await ctx.db.query(`insert into loan_contacts (name, mobile, relation, owner_id) 
        VALUES(?,?,?,?)`, [reqbodys.cname1, reqbodys.cmobile1, reqbodys.relation1, loan_user.id]);

        await ctx.db.query(`insert into loan_contacts (name, mobile, relation, owner_id) 
        VALUES(?,?,?,?)`, [reqbodys.cname2, reqbodys.cmobile2, reqbodys.relation2, loan_user.id]);

    }

    response(ctx, 200, '', '保存借款个人信息成功');
})

/**
 * @api {post} /api/v1/user/saveuserface  保存活体检测信息
 * @apiDescription 保存活体检测信息
 * @apiName saveuserface
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} face_image_1 活体照片1  
 * @apiParam (参数) {String} face_image_2 活体照片2   
 * @apiSampleRequest /api/v1/user/saveuserface
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/saveuserface', async ctx => {
    let { user_id, similarityValue, face_image_1, face_image_2 } = ctx.request.body;
    if (!user_id || user_id == 'undefined' || user_id == '') {
        response(ctx, 201, '', '用户id不能为空');
        return;
    }
    // if (!similarityValue || similarityValue == 'undefined' || similarityValue == '') {
    //     response(ctx, 201, '', '活体检测分数不能为空');
    //     return;
    // }
    if (!face_image_1 || face_image_1 == 'undefined' || face_image_1 == '') {
        response(ctx, 201, '', '活体检测照片1不能为空');
        return;
    }
    if (!face_image_2 || face_image_2 == 'undefined' || face_image_2 == '') {
        response(ctx, 201, '', '活体检测照片2不能为空');
        return;
    }
    let userdata = await db.queryone(ctx, 'auth_user', 'phone_number', { id: user_id });
    if (!userdata) {
        response(ctx, 201, '', '未找到用户信息');
        return;
    }
    let mobile = userdata.phone_number;
    let loan_user = await db.queryone(ctx, 'loan_user', 'id,info_id', { mobile: mobile});
    // 更新活体照片
    let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    if (loan_user) {
        let strsql = `Update loan_user set updated_time= '${datenow}',face_image_1='${face_image_1}',face_image_2='${face_image_2}' where id = ${loan_user.id}`;
        await ctx.db.query(strsql);
    }

    // 更新活体检测分数
    // if (loan_user) {
    //     try {
    //         let jdata = {
    //             loan_user_id: loan_user.id
    //         };
    //         var options = {
    //             method: 'post',
    //             url: ctx.config.faceapi,
    //             json: jdata,
    //             headers: {
    //                 'Content-Type': 'application/json',
    //                 'Accept': 'application/json'
    //             }
    //         }
    //         let res = await koa2Req(options);
    //         console.log("获取活体检测分数:" + res);
    //         if (res.code == 0) {
    //             let strsql = `Update loan_user_info set updated_time= '${datenow}',similarityValue='${res.code}' where id = ${loan_user.info_id}`;
    //             await ctx.db.query(strsql);
    //         }
    //     } catch (error) {
    //         console.log(error);
    //     }
    // }

    response(ctx, 200, '', '保存活体检测信息成功');
})


//获取推荐产品
async function getProlist(mobile,channel) {
    var options = {
        method: 'get',
        //url: 'https://www.uongcepat.com/loan/app/loan_products?mobile='+mobile,
        url: 'http://market.test.janesi.cn/loan/app/loan_products?mobile='+mobile,
        headers: {
            'Accept': 'application/json',
            'channel':channel
        }
    }
    let res = await koa2Req(options);
    res = JSON.stringify(res)
    res = JSON.parse(res)
    return res;
}

//发送验证码
async function sendmessage(jsondata, smsurl) {
    var options = {
        method: 'post',
        url: smsurl,
        json: jsondata,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }
    let res = await koa2Req(options);
    return res;
}



//校验验证码
async function checkvcode(phone, vcode) {
    let returnmsg = {};
    let lastsendtime = await mydb.query(`SELECT created_time from sms_log where mobile=? and content=?  order by created_time desc LIMIT 1`, [phone, vcode]);
    if (lastsendtime.length == 0) {
        returnmsg.code = 201;
        returnmsg.msg = '验证码错误';
        return returnmsg;
    }
    lastsendtime = JSON.stringify(lastsendtime)
    lastsendtime = JSON.parse(lastsendtime)
    const currenttime = new Date();
    lastsendtime = new Date(lastsendtime[0].created_time)
    console.log(lastsendtime);
    let diffminutes = dateformat.differenceInMinutes(currenttime, lastsendtime)
    if (diffminutes > 1) {
        returnmsg.code = 201;
        returnmsg.msg = '验证码过期';
    } else {
        returnmsg.code = 200;
        returnmsg.msg = '验证码正确';
    }
    return returnmsg;
}

/**
 * @api {post} /api/v1/user/isfirstinstall  用户隐私协议
 * @apiDescription 检测是否首次安装弹出隐私协议
 * @apiName isfirstinstall
 * @apiParam (参数) {String} device_id   设备号
 * @apiSampleRequest /api/v1/user/isfirstinstall
 * @apiGroup user
 * @apiVersion 1.0.0
 */
router.post('/isfirstinstall', async ctx => {
    let { device_id } = ctx.request.body;
    let selectStr = ' id,username,nickname,phone_number,channel,login_channel,is_notice,push_token ';
    // let whereStr = ` device_id=${device_id} `;
    let user = await db.queryone(ctx, 'auth_user', selectStr, { device_id: device_id });
    // 已安装，返回设备用户昵称
    if (user) {
        response(ctx, 200, user, '已安装，返回用户信息');
        // ctx.body = common.handleResulte(200, user, '已安装，返回用户信息');
    } else { // 未安装，跳出隐私协议
        let selectStr = ' package_name,channel_name,app_name,description,privacy_agreement,channel_agreement_terms_link,loan_agreement_link,is_switch,stop_time,is_login,apk_download_link,channel_type,country_id ';
        // let whereStr = ` channel_name = ${ctx.config.appname} `;
        let data = await db.queryone(ctx, 'content_channel', selectStr, { channel_name: user.channel });
        // ctx.body = common.handleResulte(200, data, '未安装，返回隐私协议信息');
        response(ctx, 200, data, '未安装，返回隐私协议信息');
    }
})

/**
* @api {post} /api/v1/user/querytags  获取标签
* @apiDescription 获取标签
* @apiName querytags
* @apiParam (参数) {String} countryname   国家名称
* @apiSampleRequest /api/v1/user/querytags
* @apiGroup user
* @apiVersion 1.0.0
*/
router.post('/querytags', async ctx => {
    let { countryname } = ctx.request.body;
    let sqlStr = `SELECT a.name,a.is_active FROM content_tag a, country_country b WHERE a.country_id = b.id AND  b.name='${countryname}'`
    let tags = await db.querysql(ctx, sqlStr);
    // ctx.body = common.handleResulte(200, tags, '获取本地区标签');
    response(ctx, 200, tags, '获取本地区标签');
})

/**
* @api {post} /api/v1/user/getperiod  获取贷款额度
* @apiDescription 获取贷款额度
* @apiName getperiod
* @apiParam (参数) {String} user_id   用户id
* @apiParam (参数) {String} package_name   包名
* @apiSampleRequest /api/v1/user/getperiod
* @apiGroup user
* @apiVersion 1.0.0
*/
router.post('/getperiod', async ctx => {
    let { user_id,package_name } = ctx.request.body;
    package_name='com.skeytks.uhnetc'
    //package_name='com.vn.gethoa.cho'
    //当前贷款用户
    let auth_user= await ctx.db.query(`select a.channel,a.phone_number,b.id_card_number,b.id from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`,[parseInt(user_id)])
    auth_user=auth_user[0];
    auth_user.channel=package_name;
    // 排除的产品
    let product_ids = [];

    //冷热区
    //let rate_li = await prate.api_optimization(ctx, auth_user.channel, null, []);
     //接口获取
    let rate_li=await getProlist(auth_user.phone_number,package_name);
    let pres=JSON.parse(rate_li.body);
    console.log(pres);
    if(pres.detail=="身份认证信息未提供"||pres.detail=="Authentication credentials were not provided."){
        response(ctx, 300, null, "未获取到产品");
        return;
    }
    if(pres.length==0){
        
        response(ctx, 300, null, '未获取到产品');

        return;
    }
    let result = [];
    for (let index = 0; index < pres.length; index++) {
        const pro = pres[index].id;
//     //1、当已推送过有无结清的过滤掉
//      //let nopayment=await ctx.db.query('select * from loan_order where user_id=? and product_id=? and pull_status=1 and order_status<>200',[auth_user.id,pro[0]])
     
//      //已推送
//     //let haspull=await ctx.db.query('select * from loan_order where user_id=? and product_id=? and pull_status=1 and order_status<>200',[auth_user.id,pro[0]])

//      //过滤未结清的
//      let nopayment=await ctx.db.query('select * from loan_order where user_id=? and product_id=? and  order_status<>200',[auth_user.id,pro[0]])
//     if(nopayment.length>0){
//         continue;
//     }

//     //2、当该用户被预审拒绝的不再推送给客户

//     let nopass= await ctx.db.query('select * from loan_order where user_id=? and product_id=? and order_status=110',[auth_user.id,pro[0]])
//     if(nopass.length>0){
//         continue;
//     }
//     //3、当该用户被黑名单（如果有此数据，该条规则生效）命中的不再推送给客户；
//      //package_name='com.whale.rise.market'
//     let inwblist= await ctx.db.query('select * from content_channel a,white_black_list b where a.id=b.channel_id and b.product_id=? AND a.package_name=? and b.type=1',[pro[0],package_name])
//     if(inwblist.length>0){
//         continue;
//     }
//   //5、当客户当天推送订单数达到限流数的，过滤掉； 
//   let xllist=await ctx.db.query(`select * from loan_order  where pull_status=1 AND DATE_FORMAT(push_date,'%m-%d-%Y')=DATE_FORMAT(NOW(),'%m-%d-%Y') and product_id=?`,[pro[0]])
//   let xlpro=await ctx.db.query('select * from products_product  where id=?',[pro[0]])
//   if(xllist.length>0){
//       if(xlpro.length>0){
//          if(xlpro[0].limit_num!=0){
//             if(xllist.length>=  xlpro[0].limit_num){
//                 continue;
//              }
//          }
        
//       }
//   }

        //构造产品数据
        let a = await getpri(ctx, pro, auth_user);

        result = _.union(result, a);
    }

    if (result.length > 0) {
        let amount = 0;
        result.map((a) => {
            if (a && a.loan_amount) {
                amount += parseInt(a.loan_amount);
            }
        });
        let resdata = {
            amount: amount,
            items: result
        };
        response(ctx, 200, resdata, '返回用户贷款额度');
    } else {
        // 无产品推荐
        //let res=await getproduct(auth_user.channel);
        response(ctx, 300, null, '贷款已经处理，只能在贷款完成后再申请。');
    }
})




/**
* @api {post} /api/v1/user/editperiod  调整额度
* @apiDescription 调整额度
* @apiName editperiod
* @apiParam (参数) {String} loan_mount   贷款额度
* @apiParam (参数) {String} period   贷款期限
* @apiParam (参数) {String} id   产品id
* @apiSampleRequest /api/v1/user/editperiod
* @apiGroup user
* @apiVersion 1.0.0
*/
router.post('/editperiod', async ctx => {
    let { loan_mount, period, id } = ctx.request.body;
    let result = {
        id: id,
        loan_mount: loan_mount,
        period: period
    };
    //获取当前产品信息
    let products_product = await db.queryone(ctx, 'products_product', 'rate,admin_amount,api_amount,loan_type,loan_rate,admin_amount_type', { id: id });
    //扩展额度
    let parli=`SELECT loan_amount,period,admin_amount,rate from product_loan_quota  WHERE product_id=${id} and loan_amount=${loan_mount} and period=${period}`
    let parli3 = await ctx.db.query(parli);
   
    if (products_product) {
        let quota={};
        if(products_product.api_amount==1){
           quota= parli3[0];
        }

        if(products_product.api_amount==0){
            quota= products_product;
         }
      
        /** 管理费计算方式    (0, '本金*天数*管理利率'), (1, '本金*管理利率'), (2, '固定金额') */
        let admin_mount = 0;
        switch (products_product.admin_amount_type) {
            case 0:
                admin_mount = common.mul(common.mul(loan_mount, quota.admin_amount), period);
                break;
            case 1:
                admin_mount = common.mul(loan_mount, quota.admin_amount);
                break;
            case 2:
                admin_mount = quota.admin_amount;
                break;
            default:
                //admin_mount = products_product.admin_amount;
                break;
        }
        /** 计算利息 loan_rate利率*/
        let lmount = common.mul(common.mul(loan_mount, quota.rate), period);

        /** 贷款模式      (0, _('预扣利息模式')), (1, _('非预扣利息模式')) */
        switch (products_product.loan_type) {
            // 计算实际到账金额和总还款额
            case 0:
                // 实际到账金额 = 额度-利息-管理费
                result.actual_amount = common.sub(common.sub(loan_mount, lmount), admin_mount);
                // 总还款额=本金
                result.repay_total_amount = loan_mount;
                break;
            case 1:
                // 实际到账金额 = 额度-管理费
                result.actual_amount = common.sub(loan_mount, admin_mount);
                // 总还款额=本金+利息
                result.repay_total_amount = common.add(loan_mount, lmount);
                break;
            default:
                break;
        }

        // 利息+管理费
        result.admin_amount = common.add(lmount, admin_mount);

        response(ctx, 200, result, '返回调整后额度信息');
    } else {
        response(ctx, 201, '', '未找到产品配置信息，请联系管理员');
    }
})


async function getpri(ctx, proid, loan_user) {

  //当前产品信息
  let products_product = await db.queryone(ctx, 'products_product', "name,images,appid,domain,api_contract,api_amount,`key`,rate,admin_amount,loan_type,loan_rate,admin_amount_type,api_amount", { id: proid });
  //额度
  let sql = `SELECT b.amount as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=${proid} order by b.amount`;
  let amountitems = await ctx.db.query(sql);
  //期限
  let sql2 = `SELECT a.period FROM products_loanperiod a, products_product_period b WHERE  a.id=b.loanperiod_id AND b.product_id=${proid} order by a.period`;
  let proiditems = await ctx.db.query(sql2);
 
 //扩展额度
 let  plqstr=`SELECT loan_amount,period,admin_amount,rate from product_loan_quota  WHERE product_id=${proid} order by loan_amount`
 let parli3 = await ctx.db.query(plqstr);
 
 


  if (products_product) {

    // let quota={};
    //     if(products_product.api_amount==1){
    //        quota= parli3[0];
    //     }

    //     if(products_product.api_amount==0){
    //         quota= products_product;
    //      }
      let data = [
          {
              'loan_amount': amountitems[0].amount,
              'period': proiditems[0].period,
              'actual_amount': 0,
              'repay_total_amount': 0
          }
      ];

     
      if (data) {
          let result = data.map((a) => {
              /** 管理费计算方式    (0, '本金*天数*管理利率'), (1, '本金*管理利率'), (2, '固定金额') */
              let admin_mount = 0;
              switch (products_product.admin_amount_type) {
                  case 0:
                      admin_mount = common.mul(common.mul(a.loan_amount, products_product.admin_amount), a.period);
                      break;
                  case 1:
                      admin_mount = common.mul(a.loan_amount, products_product.admin_amount);
                      break;
                  case 2:
                      admin_mount = products_product.admin_amount;
                      break; 
                  default:
                      //admin_mount = products_product.admin_amount;
                      break;
              }
              /** 计算利息 loan_rate利率*/
              let lmount = common.mul(common.mul(a.loan_amount, products_product.rate), a.period);

              /** 贷款模式      (0, _('预扣利息模式')), (1, _('非预扣利息模式')) */
              switch (products_product.loan_type) {
                  // 计算实际到账金额和总还款额
                  case 0:
                      // 实际到账金额 = 额度-利息-管理费
                      a.actual_amount = common.sub(common.sub(a.loan_amount, lmount), admin_mount);
                      // 总还款额=本金
                      a.repay_total_amount = a.loan_amount;
                      break;
                  case 1:
                      // 实际到账金额 = 额度-管理费
                      a.actual_amount = common.sub(a.loan_amount, admin_mount);
                      // 总还款额=本金+利息
                      a.repay_total_amount = common.add(a.loan_amount, lmount);
                      break;
                  default:
                      break;
              }
              a.api_contract=products_product.api_contract;
              // 利息+管理费
              a.admin_amount = common.add(lmount, admin_mount);
              //a.admin_amount = admin_mount;
              // a.admin_amount_type = products_product.admin_amount_type;
              // a.rate = products_product.rate;
              // a.admin_amount = products_product.admin_amount;
              // a.loan_type = products_product.loan_type;
              a.id = proid;
              a.api_amount=products_product.api_amount;
              a.name = products_product.name;
              if (products_product.images)
                  a.image = ctx.config.productimgurl + products_product.images;
              let amountitemsarr=[];
          
                  parli3.map((a) => {

                    let td={
                      amount:a.loan_amount,
                      dict:{
                        period:a.period,
                        rate:a.loan_rate
                      }
                    }
                    amountitemsarr.push(td);

                  });

            //无扩展额度
            if(products_product.api_amount==0){
                a.amountitems = amountitems;
                a.proiditems = proiditems;
            }

            //有扩展额度
            if(products_product.api_amount==1){
                a.amountitems = amountitemsarr;
                a.proiditems = [];
            }
             
              a.loan_amount_msg = lang(ctx, '贷款额度');
              a.period_msg = lang(ctx, '贷款期限');
              a.actual_amount_msg = lang(ctx, '实际到账金额');
              a.repay_total_amount_msg = lang(ctx, '总还款额');
              a.admin_amount_msg = lang(ctx, '利息+管理费');
              a.amountitems_msg = lang(ctx, '额度数组');
              a.proiditems_msg = lang(ctx, '期限数组');
              return a;
          });
          return result;
      } else {
          return [];
      }
  }
}



async function getproduct(channel) {
    let selectStr = `SELECT c.id,c.name,c.package_name,c.is_googleplay_package,c.loan_currency,c.loan_type,c.loan_rate,c.product_type
    ,c.product_jump_type,c.product_uri,c.images,c.promotion_icon,c.feature,c.button_content,c.product_image
     AS count FROM moduleconfig_channelpackage a  ,moduelconfig_product b ,products_product c
    WHERE a.channel='${channel}' AND a.module_id= b.module_id AND b.product_id=c.id 
    LIMIT 0, 2`;
    let data = await db.querysql(ctx, selectStr);

    let sqlmin = 'SELECT min(b.amount) as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=';
    let sqlmax = 'SELECT max(b.amount) as  amount from products_product_loan_amount a,products_loanamount b WHERE a.loanamount_id = b.id AND a.product_id=';

    let newrows = [];
    let i = 0;
    for (let index = 0; index < data.length; index++) {
        let item = data[index];
        item.images = ctx.config.fileurl + item.images;
        item.product_image = ctx.config.fileurl + item.product_image;
        item.promotion_icon = ctx.config.fileurl + item.promotion_icon;
        let mindata = await db.querysql(ctx, sqlmin + item.id);
        let maxdata = await db.querysql(ctx, sqlmax + item.id);
        let min = 0;
        let max = 0;
        if (mindata.length > 0) {
            min = mindata[0].amount ? mindata[0].amount : 0;
        }
        if (maxdata.length > 0) {
            max = maxdata[0].amount ? maxdata[0].amount : 0;
        }
        item.amount_range = min + '~' + max;
        newrows.push(item);
    }
    return newrows;
}

//用户前置
async function userqualifit(user_id,productid){
 try{
  //根据手机号获取借款人信息
    //   let loan_user = await mydb.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [parseInt(user_id)]);
    //   let deviceinfo=await mydb.query(`select * from device_info where user_id=?`, [parseInt(user_id)]);
    //   let product=await mydb.query(`select * from products_product where id=?`, [parseInt(productid)]);

    //   //loan_user=JSON.stringify(loan_user);
    //   let postobj={
    //       appId:product[0].appid,
    //       credentialNo:loan_user[0].id_card_number,
    //       credentialType:'KTP',
    //       imei:deviceinfo[0].imei||random(16),
    //       mobile:loan_user[0].mobile,
    //       proudctIds:[product[0].partner_id]
    //   };

    //   postobj = common.signjsapi(postobj, product[0].key);
    //     var options = {
    //         method: 'post',
    //         url: product[0].domain + '/apply_api/qualification',
    //         json:postobj,
    //         headers: {
    //             'Content-Type': 'application/json',
    //             'Accept': 'application/json'
    //         }
    //     }
      
    //     let res = await koa2Req(options);
    //     //let  res = await common.webclient(product[0].domain + '/apply_api/qualification', postobj, 'post', ctx);
    //     // res = JSON.stringify(res)
    //     // res = JSON.parse(res)
    //     if(res.body.code==0){
    //       if(res.body.data[0].isReceived){
    //        return {code:200}
    //       }else{
    //         return {code:201}
    //       }
    //     }else{
    //       return {code:201}
    //     }
    return {code:200}

} catch (error) {
  return {code:201}
}


}
module.exports = router.routes()